class Solution
{
    int tmp[50001];
public:
    int mergesort(vector<int>& record, int left, int right)
    {
        if (left >= right) return 0;
        int ret = 0;

        int mid = (left + right) >> 1;
        ret += mergesort(record, left, mid);
        ret += mergesort(record, mid + 1, right);

        int i = 0, cur1 = left, cur2 = mid + 1;
        while (cur1 <= mid && cur2 <= right)
        {
            if (record[cur1] <= record[cur2])
            {
                tmp[i++] = record[cur1++];
            }
            else
            {
                ret += (mid - cur1 + 1);
                tmp[i++] = record[cur2++];
            }
        }
        while (cur1 <= mid) tmp[i++] = record[cur1++];
        while (cur2 <= right) tmp[i++] = record[cur2++];
        for (int j = left; j <= right; j++)
        {
            record[j] = tmp[j - left];
        }
        return ret;
    }
    int reversePairs(vector<int>& record)
    {
        return mergesort(record, 0, record.size() - 1);
    }
};
class Solution
{
    vector<int> tmp;
public:
    void mergeSort(vector<int>& nums, int left, int right)
    {
        if (left >= right) return;
        int mid = (left + right) / 2;
        //[left, mid][mid+1,right]
        mergeSort(nums, left, mid);
        mergeSort(nums, mid + 1, right);
        int i = 0, cur1 = left, cur2 = mid + 1;
        while (cur1 <= mid && cur2 <= right)
        {
            tmp[i++] = nums[cur1] <= nums[cur2] ? nums[cur1++] : nums[cur2++];
        }
        while (cur1 <= mid) tmp[i++] = nums[cur1++];
        while (cur2 <= right) tmp[i++] = nums[cur2++];

        for (int k = left; k <= right; k++)
            nums[k] = tmp[k - left];
    }
    vector<int> sortArray(vector<int>& nums)
    {
        tmp.resize(nums.size());
        mergeSort(nums, 0, nums.size() - 1);
        return nums;
    }
};